package com.doform.android.xianggucheng.activity.library;

import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.activity.BaseTitleActivity;
import com.doform.android.xianggucheng.bean.InLibraryAllBean;
import com.doform.android.xianggucheng.bean.InLibraryDetailBean;
import com.doform.android.xianggucheng.bean.InLibraryDetailBean2;
import com.doform.android.xianggucheng.bean.LibraryBean2;
import com.doform.android.xianggucheng.bean.request_bean.ReqListInLibraryBean2;
import com.doform.android.xianggucheng.bean.request_bean.ReqQueryLibraryBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqUpdateInLibrary;
import com.doform.android.xianggucheng.retrofit.ApiSpecTransformer.DialogTransformer;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.utils.Constans;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.BiFunction;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者 Y_MS
 * Created by ${APEN} on 2017-08-15.
 * GitHub：https://github.com/cxydxpx
 */

public class InLibraryUpdateActivity extends BaseTitleActivity {

    @BindView(R.id.et_code)
    TextView et_code;

    @BindView(R.id.et_type)
    TextView et_type;

    @BindView(R.id.et_clear_type)
    TextView et_clear_type;

    @BindView(R.id.et_time)
    TextView et_time;

    @BindView(R.id.et_library)
    TextView et_library;

    @BindView(R.id.et_caigouren)
    TextView et_caigouren;

    @BindView(R.id.et_zhidanren)
    TextView et_zhidanren;

    @BindView(R.id.et_money)
    TextView et_money;

    @BindView(R.id.et_remark)
    TextView et_remark;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;


    @BindView(R.id.btn_submit)
    Button btn_sumbit;

    private CommonAdapter<InLibraryDetailBean2.ListBean> mCommonAdapter;
    private List<InLibraryDetailBean2.ListBean> mDatas = new ArrayList<>();

    private String mId;
    private String mGuid;

    @Override
    protected void init() {
        super.init();
        LibraryBean2.ListBean bean = (LibraryBean2.ListBean) getIntent().getSerializableExtra(Constans.EXTRA_INlIBRARY_UPDATE);
        String gone = getIntent().getStringExtra(Constans.EXTRA_INlIBRARY_UPDATE_GONE);

        if (gone != null) {
            btn_sumbit.setVisibility(View.GONE);
        } else {
            btn_sumbit.setVisibility(View.VISIBLE);
        }

        if (bean != null) {
            mId = bean.getId();
            mGuid = bean.getGuid();
        }
    }

    @Override
    protected int layoutResId() {
        return R.layout.activity_inlibrary_update;
    }

    @Override
    protected void initView() {
        super.initView();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    protected void showView() {
        titleBar.setTextTitle("采购单详情");
    }

    @Override
    protected void initListener() {
        super.initListener();

        mCommonAdapter = new CommonAdapter<InLibraryDetailBean2.ListBean>(this, R.layout.activity_new_add_library_detail_item, mDatas) {
            @Override
            protected void convert(ViewHolder holder, final InLibraryDetailBean2.ListBean dataBean, int position) {
                TextView tv_name = holder.getView(R.id.tv_name);
                TextView tv_price = holder.getView(R.id.tv_price);
                TextView tv_number = holder.getView(R.id.tv_number);
                TextView tv_sum_price = holder.getView(R.id.tv_sum_price);

                tv_name.setText(dataBean.getName());
                tv_number.setText(dataBean.getBuynum());
                tv_price.setText(dataBean.getBuyprice());
                tv_sum_price.setText(Double.valueOf(dataBean.getBuynum()) * Double.valueOf(dataBean.getBuyprice()) + "");

            }
        };

        mRecyclerView.setAdapter(mCommonAdapter);

    }

    @Override
    protected void updateData() {
        super.updateData();
        getDataForService(mId);
    }

    private void getDataForService(String mId) {
        Observable
                .zip(getInlibrary(mId), getDataDetail(mId),
                        new BiFunction<ArrayList<InLibraryDetailBean>, InLibraryDetailBean2, InLibraryAllBean>() {
                            @Override
                            public InLibraryAllBean apply(@NonNull ArrayList<InLibraryDetailBean> inLibraryDetailBeen,
                                                          @NonNull InLibraryDetailBean2 inLibraryDetailBean2) throws Exception {
                                return new InLibraryAllBean(inLibraryDetailBeen, inLibraryDetailBean2);
                            }
                        }
                ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(new DialogTransformer<InLibraryAllBean>(mProgressBar))
                .subscribe(new ErrorHandleSubscriber<InLibraryAllBean>() {
                               @Override
                               public void onNext(@NonNull InLibraryAllBean inLibraryAllBean) {
                                   InLibraryDetailBean2 listBean = inLibraryAllBean.getBean();
                                   ArrayList<InLibraryDetailBean> list = inLibraryAllBean.getList();
                                   updateUi(list.get(0), listBean.getList());

                               }
                           }
                );
    }

    /**
     * 获取采购单
     *
     * @param mId
     * @return
     */
    private Observable<ArrayList<InLibraryDetailBean>> getInlibrary(String mId) {
        return HttpManager
                .instance()
                .getInLibraryDetail(new ReqQueryLibraryBean(mId));
    }

    /**
     * 获取采购单明细
     *
     * @param id
     */
    private Observable<InLibraryDetailBean2> getDataDetail(String id) {
        return HttpManager
                .instance()
                .getInLibraryListDetail(new ReqListInLibraryBean2(id));
    }

    private String id;
    private String guid;
    private String mLibraryId;
    private String mLibraryName;
    private String mClearTypeId;
    private String mTime;
    private String mPerson;
    private String mRemark;

    private void updateUi(InLibraryDetailBean data, List<InLibraryDetailBean2.ListBean> list) {
        /**
         * 当修改的时候 进来可直接显示已有的数据
         *
         * @param data
         */

        id = data.getId();
        guid = data.getGuid();

        mClearTypeId = data.getMethod();

        switch (mClearTypeId) {
            case "1":
                et_clear_type.setText("现金");
                break;
            case "2":
                et_clear_type.setText("账期");
                break;
        }

        et_code.setText(id);

        mLibraryId = data.getWhid();
        mLibraryName = data.getWhname();

        et_library.setText(mLibraryName);//仓库

        mTime = data.getBuydate();

        et_time.setText(mTime);

        mPerson = data.getApname();
        et_caigouren.setText(mPerson);

        mRemark = data.getRemark();
        et_remark.setText(mRemark);

        et_money.setText(data.getMoney());

        mDatas.clear();
        mDatas.addAll(list);
        mCommonAdapter.notifyDataSetChanged();
    }


    private void beforeSubmit() {
        HttpManager
                .instance()
                .updateInLibrary(new ReqUpdateInLibrary(id, guid, mLibraryId, mLibraryName, mClearTypeId,
                        mTime, mPerson, mRemark, "7"))
                .subscribe(new ErrorHandleSubscriber<Integer>() {
                    @Override
                    public void onNext(@NonNull Integer integer) {
                        Intent intent = new Intent();
                        intent.putExtra(Constans.EXTRA_IN_LIBRARY_TYPE, "7");
                        setResult(Constans.REQUEST_IN_LIBRARY, intent);
                        finish();
                    }
                });
    }


    @OnClick({R.id.btn_submit})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                beforeSubmit();
                break;
            default:
                break;
        }
    }


}
